package com.fortune.controller;
import java.math.BigDecimal;
import java.util.List;

import com.fortune.base.BaseController;
import com.fortune.dto.excution.COrderExcution;
import com.fortune.dto.in.cOrder.*;
import com.fortune.entity.COrderPolicy;
import com.fortune.enums.COrderEnum;
import com.fortune.exception.db.DeleteInnerErrorException;
import com.fortune.exception.db.InsertInnerErrorException;
import com.fortune.service.COrderService;
import com.fortune.util.UUIDUtil;
import com.fortune.vo.cOrder.*;
import io.swagger.annotations.*;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fortune.base.BaseAPIExcution;
import com.fortune.common.paging.PagingData;

import springfox.documentation.annotations.ApiIgnore;


@Api(value = "cOrder", description = "客户订单", tags = {"微信小程序（客户）：订单相关"})
@RestController
@RequestMapping("cOrder")
@Validated
public class COrderController extends BaseController{
	@Autowired
	private COrderService cOrderService;

	@ApiOperation(value = "获取商品列表", nickname = "cOrderProducts", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @GetMapping(value = "products",
        produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<List<ClientOrderProduct>> products() {
		String mid = getMId();
		List<ClientOrderProduct> findListOrderProductInfo = cOrderService.findListOrderProductInfo(mid);
		for(int i = 0; i < findListOrderProductInfo.size(); i++){
			ClientOrderProduct clientOrderProduct = findListOrderProductInfo.get(i);
			String mpid = clientOrderProduct.getId();
			COrderPolicy findListCOrderPolicy = cOrderService.findListCOrderPolicy(mid,mpid);
			if(findListCOrderPolicy != null){
				String policyId = findListCOrderPolicy.getPolicyId();
				String policyName = findListCOrderPolicy.getPolicyName();
				float achieveNum = findListCOrderPolicy.getAchieveNum();
				float giftnum = findListCOrderPolicy.getGiftnum();
				clientOrderProduct.setPolicyId(policyId);
				clientOrderProduct.setPolicyName(policyName);
				clientOrderProduct.setAchieveNum(achieveNum);
				clientOrderProduct.setGiftnum(giftnum);
			}
		}
		return new COrderExcution<List<ClientOrderProduct>>(findListOrderProductInfo, COrderEnum.FIND_SUCCESS);
	}
	
	@ApiOperation(value = "提交订单", nickname = "cOrderSubmit", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @PostMapping(value = "add",
        produces = { MediaType.APPLICATION_JSON_VALUE },
        consumes = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<CorderSubmit> add(@Validated @RequestBody COrderSubmitDto addDto) {
		String mid = getMId();
		String did = getMId();
		String userId = getUserId();
		COrderProductDto products = addDto.getProducts();
		String clientId = products.getClientId();//客户id
		String id = UUIDUtil.get32UUID();//订单id
		String no = UUIDUtil.get32UUID();//订单编号
		String productId = products.getProductId();//商品ID
		//int num = products.getNum();//总商品数量
		List<PurchaseGiftDto> sales = products.getSales();//销售
		List<PurchaseGiftDto> gift = products.getGift();//赠送
		//int backBox = products.getBackBox();//回空箱数量
		BigDecimal pTotalPrice = products.getdTotalPrice();//商品总钱数
		BigDecimal dTotalPrice = products.getdTotalPrice();//押金钱数
		int addCOrder = cOrderService.addCOrder(mid, did, clientId, id, no, userId, pTotalPrice, dTotalPrice);
		if(addCOrder < 0){
			throw new InsertInnerErrorException("添加失败！");
		}
		CorderSubmit corderSubmit = new CorderSubmit();
		corderSubmit.setId(id);
		corderSubmit.setNo(no);

		int a = 0;
		//销售
		for(int j = 0; j < sales.size(); j++){
			PurchaseGiftDto purchaseGiftDto = sales.get(j);
			int detailsNo = a + 1;
			a = detailsNo;
			float orderNum = purchaseGiftDto.getOrderNum();//订货数量
			BigDecimal unitPrice = purchaseGiftDto.getUnitPrice();//单价
			String policyId = purchaseGiftDto.getPolicyId();//优惠政策ID
			float backBoxNum = purchaseGiftDto.getBackBoxNum();//回空箱数量
			BigDecimal dprice = purchaseGiftDto.getDprice();//押金金额
			BigDecimal price = purchaseGiftDto.getPrice();//商品金额
			BigDecimal tprice = dprice.add(price);
			int addCOrderDetails = cOrderService.addCOrderDetails(mid, did, clientId, id, detailsNo, productId, orderNum, price, policyId, unitPrice, backBoxNum, dprice, tprice);
			if(addCOrderDetails < 0){
				throw new InsertInnerErrorException("添加失败！");
			}
		}
		//赠送
		for(int x = 0; x < gift.size(); x++){
			PurchaseGiftDto purchaseGiftDto = gift.get(x);
			int detailsNo = a + 1;
			float orderNum = purchaseGiftDto.getOrderNum();//订货数量
			BigDecimal unitPrice = purchaseGiftDto.getUnitPrice();//单价
			String policyId = purchaseGiftDto.getPolicyId();//优惠政策ID
			float backBoxNum = purchaseGiftDto.getBackBoxNum();//回空箱数量
			BigDecimal dprice = purchaseGiftDto.getDprice();//押金金额
			BigDecimal price = purchaseGiftDto.getPrice();//商品金额
			BigDecimal tprice = dprice.add(price);
			int addCOrderDetailsByZS = cOrderService.addCOrderDetailsByZS(mid, did, clientId, id, detailsNo, productId, orderNum, price, policyId, unitPrice, backBoxNum, dprice, tprice);
			if(addCOrderDetailsByZS < 0){
				throw new InsertInnerErrorException("添加失败！");
			}
		}
		return new COrderExcution<CorderSubmit>(corderSubmit, COrderEnum.ADD_SUCCESS);
	}
	
	@ApiOperation(value = "编辑订单", nickname = "clientOrderEdit", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @PostMapping(value = "edit",
        produces = { MediaType.APPLICATION_JSON_VALUE },
        consumes = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<CorderSubmit> edit(@Validated @RequestBody CClientOrderEditDto editDto) {
		COrderProductEditDto products = editDto.getProducts();
		String mid = getMId();
		String did = getDId();
		String ordersId = products.getOrdersId();//订单id
		String orderNums = products.getOrderNum();//订单编号
		String clientId = products.getClientId();//客户id
		int editOrder = cOrderService.editOrder(mid, did, ordersId ,orderNums,clientId);
		if(editOrder < 1){
			throw new DeleteInnerErrorException("删除失败！");
		}
		String userId = "kh123";
		String id = UUIDUtil.get32UUID();//订单id
		String no = UUIDUtil.get32UUID();//订单编号
		String productId = products.getProductId();//商品ID
		//int num = products.getNum();//总商品数量
		List<PurchaseGiftDto> sales = products.getSales();//销售
		List<PurchaseGiftDto> gift = products.getGift();//赠送
		//int backBox = products.getBackBox();//回空箱数量
		BigDecimal pTotalPrice = products.getdTotalPrice();//商品总钱数
		BigDecimal dTotalPrice = products.getdTotalPrice();//押金钱数
		int addCOrder = cOrderService.addCOrder(mid, did, clientId, id, no, userId, pTotalPrice, dTotalPrice);
		if(addCOrder < 0){
			throw new InsertInnerErrorException("添加失败！");
		}
		CorderSubmit corderSubmit = new CorderSubmit();
		corderSubmit.setId(id);
		corderSubmit.setNo(no);

		int a = 0;
		//销售
		for(int j = 0; j < sales.size(); j++){
			PurchaseGiftDto purchaseGiftDto = sales.get(j);
			int detailsNo = a + 1;
			a = detailsNo;
			float orderNum = purchaseGiftDto.getOrderNum();//订货数量
			BigDecimal unitPrice = purchaseGiftDto.getUnitPrice();//单价
			String policyId = purchaseGiftDto.getPolicyId();//优惠政策ID
			float backBoxNum = purchaseGiftDto.getBackBoxNum();//回空箱数量
			BigDecimal dprice = purchaseGiftDto.getDprice();//押金金额
			BigDecimal price = purchaseGiftDto.getPrice();//商品金额
			BigDecimal tprice = dprice.add(price);
			int addCOrderDetails = cOrderService.addCOrderDetails(mid, did, clientId, id, detailsNo, productId, orderNum, price, policyId, unitPrice, backBoxNum, dprice, tprice);
			if(addCOrderDetails < 0){
				throw new InsertInnerErrorException("添加失败！");
			}
		}
		//赠送
		for(int x = 0; x < gift.size(); x++){
			PurchaseGiftDto purchaseGiftDto = gift.get(x);
			int detailsNo = a + 1;
			float orderNum = purchaseGiftDto.getOrderNum();//订货数量
			BigDecimal unitPrice = purchaseGiftDto.getUnitPrice();//单价
			String policyId = purchaseGiftDto.getPolicyId();//优惠政策ID
			float backBoxNum = purchaseGiftDto.getBackBoxNum();//回空箱数量
			BigDecimal dprice = purchaseGiftDto.getDprice();//押金金额
			BigDecimal price = purchaseGiftDto.getPrice();//商品金额
			BigDecimal tprice = dprice.add(price);
			int addCOrderDetailsByZS = cOrderService.addCOrderDetailsByZS(mid, did, clientId, id, detailsNo, productId, orderNum, price, policyId, unitPrice, backBoxNum, dprice, tprice);
			if(addCOrderDetailsByZS < 0){
				throw new InsertInnerErrorException("添加失败！");
			}
		}
		return new COrderExcution<CorderSubmit>(corderSubmit, COrderEnum.ADD_SUCCESS);
	}
	
	@ApiOperation(value = "获取订单列表", nickname = "clientOrderList", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
		@ApiImplicitParam(name="page", value="第几页",paramType="query",dataType="int"),
		@ApiImplicitParam(name="length", value="每页容量",paramType="query",dataType="int"),
		@ApiImplicitParam(name="type", value="0未处理，1已批准，2已发货，3已收货，4已完成",paramType="query",dataType="int",allowableValues="0,1,2,3,4"),
		@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @GetMapping(value = "list",
        produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<PagingData<ClientOrder>> list(@ApiIgnore @Validated ClientOrderListByTypeDto listDto) {
		int type = listDto.getType();
        String mid = getMId();
        String did = getDId();
        String userId = getUserId();
        if(type == 0){
            List<ClientOrder> findListClientOrder = cOrderService.findListClientOrder(mid,did,userId);
            PagingData<ClientOrder> pagingData = new PagingData<ClientOrder>();
            pagingData.setData(findListClientOrder);
            if(findListClientOrder.size() == 0){
                return new COrderExcution<PagingData<ClientOrder>>(null, COrderEnum.FIND_RESULT_AIR);
            }
            return new COrderExcution<PagingData<ClientOrder>>(pagingData, COrderEnum.FIND_SUCCESS);
		}

		if(type == 1){
            List<ClientOrder> findListClientOrderByApproved = cOrderService.findListClientOrderByApproved(mid, did, userId);
            PagingData<ClientOrder> pagingData = new PagingData<ClientOrder>();
            pagingData.setData(findListClientOrderByApproved);
            if(findListClientOrderByApproved.size() == 0){
                return new COrderExcution<PagingData<ClientOrder>>(null, COrderEnum.FIND_RESULT_AIR);
            }
            return new COrderExcution<PagingData<ClientOrder>>(pagingData, COrderEnum.FIND_SUCCESS);
		}

		if(type == 2){
			List<ClientOrder> findListClientOrderByShipped = cOrderService.findListClientOrderByShipped(mid, did, userId);
            PagingData<ClientOrder> pagingData = new PagingData<ClientOrder>();
            pagingData.setData(findListClientOrderByShipped);
            if(findListClientOrderByShipped.size() == 0){
                return new COrderExcution<PagingData<ClientOrder>>(null, COrderEnum.FIND_RESULT_AIR);
            }
            return new COrderExcution<PagingData<ClientOrder>>(pagingData, COrderEnum.FIND_SUCCESS);
		}

		if(type == 3){
			List<ClientOrder> findListClientOrderByreceived = cOrderService.findListClientOrderByreceived(mid, did, userId);
			PagingData<ClientOrder> pagingData = new PagingData<ClientOrder>();
			pagingData.setData(findListClientOrderByreceived);
			if(findListClientOrderByreceived.size() == 0){
				return new COrderExcution<PagingData<ClientOrder>>(null, COrderEnum.FIND_RESULT_AIR);
			}
			return new COrderExcution<PagingData<ClientOrder>>(pagingData, COrderEnum.FIND_SUCCESS);
		}

		if(type == 4){
			List<ClientOrder> findListClientOrderByCompleted = cOrderService.findListClientOrderByCompleted(mid, did, userId);
			PagingData<ClientOrder> pagingData = new PagingData<ClientOrder>();
			pagingData.setData(findListClientOrderByCompleted);
			if(findListClientOrderByCompleted.size() == 0){
				return new COrderExcution<PagingData<ClientOrder>>(null, COrderEnum.FIND_RESULT_AIR);
			}
			return new COrderExcution<PagingData<ClientOrder>>(pagingData, COrderEnum.FIND_SUCCESS);
		}

		return new COrderExcution<PagingData<ClientOrder>>(null, COrderEnum.FIND_RESULT_AIR);
	}
	
	@ApiOperation(value = "获取已批准订单详情", nickname = "clientOrderDetail", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
			@ApiImplicitParam(name="orderId", value="订单id",paramType="query",dataType="string"),
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @GetMapping(value = "detail",
        produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<ClientOrderDetail> detail(@NotBlank(message="订单id不能为空") String orderId) {
		String mid = getMId();
		String did = getDId();
		String clientId = getUserId();
		ClientOrderDetail findClientOrderDetail = cOrderService.findClientOrderDetail(mid, did, clientId, orderId);
		if(findClientOrderDetail == null){
			return new COrderExcution<ClientOrderDetail>(null, COrderEnum.FIND_RESULT_AIR);
		}
		return new COrderExcution<ClientOrderDetail>(findClientOrderDetail, COrderEnum.FIND_SUCCESS);
	}

	@ApiOperation(value = "获取已出库详情", nickname = "clientOutLibraryDetail", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
			@ApiImplicitParam(name="orderId", value="订单id",paramType="query",dataType="string"),
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
	@GetMapping(value = "libraryDetail",
			produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<ClientOrderDetail> libraryDetail(@NotBlank(message="订单id不能为空") String orderId) {
		String mid = getMId();
		String did = getDId();
		String clientId = getUserId();
		ClientOrderDetail findClientOrderDetailByCk = cOrderService.findClientOrderDetailByCk(mid, did, clientId, orderId);
		if(findClientOrderDetailByCk == null){
			return new COrderExcution<ClientOrderDetail>(null, COrderEnum.FIND_RESULT_AIR);
		}
		return new COrderExcution<ClientOrderDetail>(findClientOrderDetailByCk, COrderEnum.FIND_SUCCESS);
	}

	@ApiOperation(value = "获取已收货详情", nickname = "clientReceiptDetail", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
			@ApiImplicitParam(name="orderId", value="订单id",paramType="query",dataType="string"),
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
	@GetMapping(value = "receiptDetail",
			produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<ClientOrderDetails> receiptDetail(@NotBlank(message="订单id不能为空") String orderId) {
		String mid = getMId();
		String did = getDId();
		String clientId = getUserId();
		ClientOrderDetails findClientOrderDetailsBySH = cOrderService.findClientOrderDetailsBySH(mid, did, clientId, orderId);
		if(findClientOrderDetailsBySH == null){
			return new COrderExcution<ClientOrderDetails>(null, COrderEnum.FIND_RESULT_AIR);
		}
		return new COrderExcution<ClientOrderDetails>(findClientOrderDetailsBySH, COrderEnum.FIND_SUCCESS);
	}

	@ApiOperation(value = "获取已完成详情", nickname = "clientCarryDetail", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
			@ApiImplicitParam(name="orderId", value="订单id",paramType="query",dataType="string"),
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
	@GetMapping(value = "carryDetail",
			produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<ClientOrderDetails> carryDetail(@NotBlank(message="订单id不能为空") String orderId) {
		String mid = getMId();
		String did = getDId();
		String clientId = getUserId();
		ClientOrderDetails findClientOrderDetailsByWC = cOrderService.findClientOrderDetailsByWC(mid, did, clientId, orderId);
		if(findClientOrderDetailsByWC == null){
			return new COrderExcution<ClientOrderDetails>(null, COrderEnum.FIND_RESULT_AIR);
		}
		return new COrderExcution<ClientOrderDetails>(findClientOrderDetailsByWC, COrderEnum.FIND_SUCCESS);
	}
	
	@ApiOperation(value = "删除订单", nickname = "clientOrderDelete", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
			@ApiImplicitParam(name="orderId", value="订单id",paramType="query",dataType="string"),
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @DeleteMapping(value = "delete",
        produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<Void> delete(@NotBlank(message="订单id不能为空") String orderId){
		String mid = getMId();
		String did = getDId();
		String clientId = getUserId();
		int deleteCOrder = cOrderService.deleteCOrder(mid, did, clientId, orderId);
		if(deleteCOrder < 0){
			return new COrderExcution<Void>(null, COrderEnum.DELETE_ERROR);
		}
		return new COrderExcution<Void>(null, COrderEnum.DELETE_SUCCESS);
	}
}
